<script setup lang="ts">
import CustomNavBar from '@/pages/index/components/CustomNavBar.vue'
import CategoryPanel from '@/pages/index/components/CategoryPanel.vue'
import HotPanel from '@/pages/index/components/HotPanel.vue'
import { onPullDownRefresh, onLoad } from '@dcloudio/uni-app'
import { getHomeBannerApi, getCategoryItemApi, getHomeHotGoodsApi } from '@/services/home.ts'
import { ref } from 'vue'
import type { BannerItem, CategoryItem, HotGoods } from '@/types/home'
// 获取首页轮播图
const HomeBannerdata = ref<BannerItem[]>([])
const getHomeBannerData = async () => {
  const res = await getHomeBannerApi()
  HomeBannerdata.value = res.result
}

// 获取商品分类
const CategoryItemList = ref<CategoryItem[]>([])
const goodsCategoryItem = async () => {
  const res = await getCategoryItemApi()
  CategoryItemList.value = res.result
}

// 获取热门商品
const HotGoodsList = ref<HotGoods[]>([])
const getHotGoods = async () => {
  const res = await getHomeHotGoodsApi()
  HotGoodsList.value = res.result
}
// 滚动触底
import { useGuessList } from '@/composables'
const { guessRef, onScrollToLower } = useGuessList()
// 加载中标记
const isLoading = ref(true)

onLoad(async () => {
  isLoading.value = true
  await Promise.all([getHomeBannerData(), goodsCategoryItem(), getHotGoods()])
  isLoading.value = false
})

onPullDownRefresh(async () => {
  // Promise.all将所有的异步操作都执行完后在执行后面的，如果是每一个一个await太浪费时间了
  await Promise.all([
    getHomeBannerData(),
    goodsCategoryItem(),
    getHotGoods(),
    guessRef.value?.refresh(),
  ])
  uni.stopPullDownRefresh()
})

// 导入骨架屏
import PageSkeleton from '@/pages/index/components/PageSkeleton.vue'
</script>

<template>
  <custom-nav-bar></custom-nav-bar>
  <scroll-view scroll-y class="scorll-view" @scrolltolower="onScrollToLower">
    <page-skeleton v-if="isLoading"></page-skeleton>
    <template v-else>
      <XtxSwiper :list="HomeBannerdata"></XtxSwiper>
      <CategoryPanel :list="CategoryItemList"></CategoryPanel>
      <HotPanel :list="HotGoodsList"></HotPanel>
      <XtxGuess ref="guessRef"></XtxGuess>
    </template>
  </scroll-view>
</template>

<style lang="scss">
//
page {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f7f7f7;
  .scroll-view {
    flex: 1;
  }
}
</style>
